<template>
  <el-card class="question-list-card" shadow="never">
    <template #header>
      <div class="card-header-container">
        <span class="card-title">题目列表</span>

        <div class="filter-bar">
          <el-popover ref="searchPopoverRef" placement="bottom" :width="230" trigger="click" class="box-item">
            <template #reference>
              <span class="el-dropdown-link">
                搜索题目 <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </span>
            </template>
            <div class="search-popover-content">
              <el-input v-model="searchQuery" placeholder="请输入题目关键词" clearable style="width: 200px" />
              <div class="popover-actions">
                <el-button @click="handleSearchClear">清除</el-button>
                <el-button type="primary" @click="handleSearchConfirm">确认</el-button>
              </div>
            </div>
          </el-popover>

          <el-dropdown @command="handleMarkedChange">
            <span class="el-dropdown-link">
              {{ markedText }} <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="" :class="{ 'is-active': queryParams.marked === undefined }"
                  >全部</el-dropdown-item
                >
                <el-dropdown-item command="0" :class="{ 'is-active': queryParams.marked === 0 }"
                  >❌未掌握</el-dropdown-item
                >
                <el-dropdown-item command="1" :class="{ 'is-active': queryParams.marked === 1 }"
                  >✅已掌握</el-dropdown-item
                >
                <el-dropdown-item command="2" :class="{ 'is-active': queryParams.marked === 2 }"
                  >⏰晚点再刷</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <el-dropdown @command="handleDifficultyChange">
            <span class="el-dropdown-link">
              {{ difficultyText }} <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="" :class="{ 'is-active': queryParams.difficulty === undefined }"
                  >全部</el-dropdown-item
                >
                <el-dropdown-item command="0" :class="{ 'is-active': queryParams.difficulty === 0 }"
                  >简单</el-dropdown-item
                >
                <el-dropdown-item command="1" :class="{ 'is-active': queryParams.difficulty === 1 }"
                  >中等</el-dropdown-item
                >
                <el-dropdown-item command="2" :class="{ 'is-active': queryParams.difficulty === 2 }"
                  >困难</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <el-dropdown @command="handleVipChange">
            <span class="el-dropdown-link">
              {{ vipText }} <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="" :class="{ 'is-active': queryParams.isVip === undefined }"
                  >全部</el-dropdown-item
                >
                <el-dropdown-item command="1" :class="{ 'is-active': queryParams.isVip === 1 }">是</el-dropdown-item>
                <el-dropdown-item command="0" :class="{ 'is-active': queryParams.isVip === 0 }">否</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <el-popover placement="bottom-start" :width="500" trigger="click" popper-class="tag-select-popper">
            <template #reference>
              <div class="tag-select-trigger">
                <div v-if="selectedTags.length > 0" class="selected-tags-container">
                  <el-tag
                    v-for="tag in selectedTags.slice(0, 2)"
                    :key="tag"
                    size="small"
                    closable
                    @close="removeTag(tag)"
                    >{{ tag }}</el-tag
                  >
                  <el-tag v-if="selectedTags.length > 2" size="small">+{{ selectedTags.length - 2 }}</el-tag>
                </div>
                <span v-else class="placeholder">可选 10 个标签, 支持搜索</span>
                <el-icon class="arrow-icon"><arrow-down /></el-icon>
              </div>
            </template>
            <div class="tag-select-panel">
              <el-tabs v-model="activeTab" class="tag-tabs">
                <el-tab-pane
                  v-for="category in tagCategories"
                  :key="category.name"
                  :label="category.name"
                  :name="category.name"
                >
                  <div class="tag-group">
                    <span
                      v-for="tag in category.tags"
                      :key="tag"
                      class="tag-item"
                      :class="{ selected: isTagSelected(tag) }"
                      @click="toggleTag(tag)"
                      >{{ tag }}</span
                    >
                  </div>
                </el-tab-pane>
              </el-tabs>
            </div>
          </el-popover>
        </div>
      </div>
    </template>

    <el-table
      :data="questionList"
      style="width: 100%"
      class="question-table"
      v-loading="loading"
      @sort-change="handleSortChange"
    >
      <!-- 标记列 -->
      <el-table-column prop="markedName" label="标记" min-width="50" align="center">
        <template #default="scope">
          {{ scope.row.markedName }}
        </template>
      </el-table-column>
      <!-- 题目列 -->
      <el-table-column prop="title" label="题目" sortable min-width="450">
        <template #default="scope">
          <router-link :to="`/bank/${getBankId()}/question/${scope.row.id}`" class="question-title-link">
            {{ scope.row.title }}
          </router-link>
        </template>
      </el-table-column>
      <!-- 难度列 -->
      <el-table-column prop="difficulty" label="难度" sortable="custom" width="120" align="center">
        <template #header>
          <el-tooltip :content="getDifficultyTooltipTextComputed()" placement="top">
            <span>难度</span>
          </el-tooltip>
        </template>
        <template #default="scope">
          <span :class="getDifficultyClass(scope.row.difficulty)">
            {{ scope.row.difficulty }}
          </span>
        </template>
      </el-table-column>
      <!-- 标签列 -->
      <el-table-column prop="tags" label="标签" min-width="200">
        <template #default="scope">
          <!-- vip标签 -->
          <el-tag v-if="scope.row.isVip" class="table-tag" type="warning" effect="dark"> vip </el-tag>
          <el-tag v-for="tag in scope.row.tags" :key="tag" class="table-tag" type="info" effect="plain">
            <a href="">{{ tag }}</a>
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        :current-page="pagination.current"
        :page-sizes="pagination.pageSizes"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        layout="total, prev, pager, next, sizes"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
</template>

<script setup lang="ts" name="QuestionList">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ArrowDown } from '@element-plus/icons-vue'
import { ElPopover } from 'element-plus'

import { QuestionListVO, TagCategoryVO, QuestionSearchParams, QuestionQuery, TagQuery } from './data.d'
import { fetchQuestionListData, fetchTagListData, useQuestionDictService, getDifficultyTooltipText } from './service'

import { useRoute, useRouter } from 'vue-router'

const questionList = ref<QuestionListVO[]>([])
const loading = ref(false)

const tagCategories = ref<TagCategoryVO[]>([])
const selectedTags = ref<string[]>([])
const activeTab = ref<string>('')

const searchQuery = ref('')
const searchPopoverRef = ref<InstanceType<typeof ElPopover> | null>(null)

const queryprops = withDefaults(defineProps<{ questionCategoryId?: string }>(), {
  questionCategoryId: '101', // 默认值
})
const queryParams = reactive<QuestionSearchParams>({
  questionCategoryId: queryprops.questionCategoryId, // 使用 props 传入的值
  sortOrder: 'desc',
})

// 监听 questionCategoryId 变化
watch(
  () => queryprops.questionCategoryId,
  (newCategoryId: string) => {
    queryParams.questionCategoryId = newCategoryId
    pagination.current = 1 // 重置到第一页
    loadQuestionData() // 重新加载数据
  }
)

const route = useRoute()
// 获取当前题库ID
const getBankId = () => {
  return route.params.id || queryprops.questionCategoryId || '101'
}

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [5, 10, 20, 30, 50],
})

// 难度排序状态
const difficultySort = ref<'asc' | 'desc' | null>(null)

// 使用字典服务
const { getDifficultyText, getVipText, getMarkedText, getDifficultyClass, initDict } = useQuestionDictService()

// 筛选文本映射（使用字典服务）
const difficultyText = computed(() => getDifficultyText(queryParams.difficulty))
const vipText = computed(() => getVipText(queryParams.isVip))
const markedText = computed(() => getMarkedText(queryParams.marked))

// 难度排序提示文本
const getDifficultyTooltipTextComputed = () => getDifficultyTooltipText(difficultySort.value)

// 加载题目数据
const loadQuestionData = async () => {
  loading.value = true
  try {
    const params: QuestionQuery = {
      current: pagination.current,
      pageSize: pagination.pageSize,
      ...queryParams,
    }

    const result = await fetchQuestionListData(params)

    questionList.value = result.list
    pagination.total = result.total
  } catch (error) {
    console.error('加载题目数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载标签数据
const loadTagData = async () => {
  try {
    const params: TagQuery = {
      current: 1,
      name: '',
      pageSize: 10,
      sortOrder: '',
    }

    const result = await fetchTagListData(params)

    // 拿到映射后的数据，更新组件状态
    tagCategories.value = result.categories

    // 设置默认选中的标签页
    if (tagCategories.value.length > 0) {
      activeTab.value = tagCategories.value[0].name
    }
  } catch (error) {
    console.error('加载标签数据失败:', error)
  }
}

// 搜索确认
const handleSearchConfirm = () => {
  queryParams.title = searchQuery.value.trim()
  pagination.current = 1 // 重置到第一页
  loadQuestionData()
  if (searchPopoverRef.value) searchPopoverRef.value.hide()
}

// 搜索清除
const handleSearchClear = () => {
  searchQuery.value = ''
  queryParams.title = ''
  pagination.current = 1
  loadQuestionData()
}

// 难度筛选
const handleDifficultyChange = (difficulty: string) => {
  queryParams.difficulty = difficulty ? parseInt(difficulty) : undefined
  pagination.current = 1
  loadQuestionData()
}

// VIP筛选
const handleVipChange = (vip: string) => {
  queryParams.isVip = vip ? parseInt(vip) : undefined
  pagination.current = 1
  loadQuestionData()
}

// 标记筛选
const handleMarkedChange = (marked: string) => {
  queryParams.marked = marked ? parseInt(marked) : undefined
  pagination.current = 1
  loadQuestionData()
}

// 标签选择逻辑
const isTagSelected = (tag: string): boolean => selectedTags.value.includes(tag)

const toggleTag = (tag: string) => {
  const index = selectedTags.value.indexOf(tag)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
  } else {
    if (selectedTags.value.length < 10) {
      selectedTags.value.push(tag)
    }
  }
  // 标签选择变化时，可以触发数据重新加载
  // loadQuestionData()
}

const removeTag = (tag: string) => {
  const index = selectedTags.value.indexOf(tag)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
  }
}

// 排序处理 - 改变查询参数
const handleSortChange = ({ prop, order }: any) => {
  if (prop === 'difficulty') {
    if (order === null) {
      // 取消排序，恢复默认排序
      difficultySort.value = null
      queryParams.sortOrder = 'desc'
    } else {
      // 设置排序字段和排序顺序
      difficultySort.value = order === 'ascending' ? 'asc' : 'desc'
      queryParams.sortOrder = order === 'ascending' ? 'asc' : 'desc'
    }

    // 跳转到第一页并重新请求数据
    pagination.current = 1
    loadQuestionData()
  }
}

// 分页大小变更
const handleSizeChange = (val: number) => {
  pagination.current = 1
  pagination.pageSize = val
  loadQuestionData()
}

// 当前页变更
const handleCurrentChange = (val: number) => {
  pagination.current = val
  loadQuestionData()
}

onMounted(async () => {
  // 字典
  initDict()

  // 加载组件数据
  await loadTagData()
  loadQuestionData()
})
</script>

<style lang="scss" scoped>
:deep(.tag-select-popper) {
  padding: 0;
}

/* 这是触发器样式 */
.tag-select-trigger {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 280px;
  height: 32px;
  padding: 0 11px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: border-color 0.2s;
}

/* 鼠标悬浮 */
.tag-select-trigger:hover {
  border-color: #c0c4cc;
}

.tag-select-trigger .placeholder {
  color: #a8abb2;
  font-size: 14px;
}

/* 已选中标签 */
.tag-select-trigger .selected-tags-container {
  display: flex;
  gap: 4px;
  overflow: hidden;
}

/* 触发器右侧的小箭头图标 */
.tag-select-trigger .arrow-icon {
  color: #a8abb2;
}

.tag-select-panel {
  padding: 8px 12px;
}

.tag-tabs :deep(.el-tabs__header) {
  margin-bottom: 12px;
}

.tag-tabs :deep(.el-tabs__nav-wrap::after) {
  display: none;
}

.tag-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 16px;
}

/* 单个标签的样式 */
.tag-item {
  cursor: pointer;
  font-size: 14px;
  color: #303133;
  padding: 2px 4px;
  border-radius: 3px;
}

.tag-item:hover {
  color: #409eff;
}

/* 标签被选中 */
.tag-item.selected {
  color: #409eff;
  background-color: #ecf5ff;
}

.question-list-card {
  border: none;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
}

/* 卡片头部 */
.question-list-card :deep(.el-card__header) {
  padding: 12px 20px;
  background-color: #f9fafb;
  border-bottom: 1px solid #e4e7ed;
}

/* 卡片内容区 */
.question-list-card :deep(.el-card__body) {
  padding-top: 20px;
}

.card-header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 标题 */
.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #1f2329;
}

/*搜素框 */
.filter-bar {
  display: flex;
  align-items: center;
  gap: 24px;
}

.el-dropdown-link {
  cursor: pointer;
  color: #606266;
  font-size: 14px;
  display: inline-flex;
  align-items: center;
}

.el-dropdown-link:hover {
  color: #409eff;
}

.search-popover-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  align-items: center;
}

.popover-actions {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.question-table :deep(th.el-table__cell) {
  border-right: none;
  background-color: #f9fafb;
  color: #646a73;
  font-weight: 500;
}

.question-table :deep(td.el-table__cell) {
  border-right: none;
}

.question-table.el-table--border {
  border: none;
}
.question-table.el-table--group {
  border: none;
}
.question-table:after {
  display: none;
}
.question-table:before {
  display: none;
}

.question-title-link {
  color: #409eff;
  text-decoration: none;
}

.question-title-link:hover {
  text-decoration: underline;
}

.difficulty-simple {
  color: #00b42a;
}
.difficulty-medium {
  color: #ff7d00;
}
.difficulty-hard {
  color: #f53f3f;
}

/* 表格内标签 */
.table-tag {
  margin-right: 8px;
  margin-bottom: 5px;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}

/* 激活状态的下拉菜单项 */
.el-dropdown-menu .el-dropdown-menu__item.is-active {
  color: #409eff;
  background-color: #ecf5ff;
}
</style>
